package com.tang.config;

import com.alibaba.fastjson.JSONObject;
import com.tang.system.vo.UserInfo;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class ShiroRealm extends AuthorizingRealm {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JwtToken token = (JwtToken) authenticationToken;
        String tokenStr = token.getToken();
        JSONObject o = (JSONObject) redisTemplate.opsForValue().get(tokenStr);
        if (Objects.isNull(o)) {
            throw new RedirectLoginException("您已经登录超时, 请登录");
        }
        redisTemplate.expire(tokenStr, 30, TimeUnit.MINUTES);
        token.setPrincipal(o.toJavaObject(UserInfo.class));
        return new SimpleAuthenticationInfo(token.getPrincipal(), token.getToken(), token.getPrincipal().getRealname());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }
}
